package cn.phantom.jmm;

class MovieTicket {

}

class House {
    int i = 0;
    ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);
//    ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
//        @Override
//        protected Integer initialValue() {
//            return 0;
//        }
//    };

    public void saleHouse() {
        Integer value = threadLocal.get();
        value++;
        threadLocal.set(value);
    }
}

public class ThreadLocalDemo01 {
    public static void main(String[] args) {
        House house = new House();

        new Thread(() -> {
            try {
                for (int i = 0; i < 3; i++) {
                    house.saleHouse();
                }
                System.out.println(Thread.currentThread().getName() + "\t" + "----卖出：" + house.threadLocal.get());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                house.threadLocal.remove();
            }
        }, "t1").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                house.saleHouse();
            }
            System.out.println(Thread.currentThread().getName() + "\t" + "----卖出：" + house.threadLocal.get());
        }, "t2").start();

        new Thread(() -> {
            for (int i = 0; i < 7; i++) {
                house.saleHouse();
            }
            System.out.println(Thread.currentThread().getName() + "\t" + "----卖出：" + house.threadLocal.get());
        }, "t2").start();

        System.out.println(Thread.currentThread().getName() + "\t" + "----卖出：" + house.threadLocal.get());
    }
}
